package com.dogsong.liteflow.editor.parser.el;

import cn.hutool.core.util.StrUtil;
import com.dogsong.liteflow.editor.bean.CmpProperty;
import com.dogsong.liteflow.editor.enums.ExpressParserEnum;
import com.dogsong.liteflow.editor.parser.base.AbstractLoopExpressParser;
import com.yomahub.liteflow.enums.ConditionTypeEnum;
import com.yomahub.liteflow.flow.element.Condition;
import com.yomahub.liteflow.flow.element.Node;
import com.yomahub.liteflow.flow.element.condition.IteratorCondition;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.Optional;

/**
 * 迭代循环解析
 *
 * @author: Young
 * @date: 2024/12/13
 */
@Component
public class IteratorConditionParser extends AbstractLoopExpressParser {

    @Override
    public ConditionTypeEnum parserType() {
        return ConditionTypeEnum.TYPE_ITERATOR;
    }

    @Override
    public ExpressParserEnum getExpressType(Condition condition) {
        return ExpressParserEnum.ITERATOR;
    }

    @Override
    public CmpProperty builderCondition(Condition condition) {
        IteratorCondition iteratorCondition = (IteratorCondition) condition;
        Node iteratorNode = iteratorCondition.getIteratorNode();
        // Node 转 CmpPropertyVO
        return Optional.of(iteratorNode).map(nodeMapper).orElse(new CmpProperty());
    }

    @Override
    public String generateELMethod(CmpProperty jsonEl) {
        return elIteratorMethod;
    }

    @Override
    public String generateCondition(CmpProperty jsonEl, String elExpress) {
        if (Objects.isNull(jsonEl.getCondition())) {
            return elExpress;
        }
        CmpProperty condition = jsonEl.getCondition();
        return StrUtil.replaceFirst(elExpress, "{}", condition.getId());
    }

    @Override
    public String generateBreak(CmpProperty jsonEl, String elExpress) {
        return elExpress;
    }
}
